import { defineStore } from 'pinia';
import { fabric } from '@/utils/fabricWrapper';
import { eventBus } from '@/utils/eventBus';
import type { HistoryItem, ActionType } from '@/types';

interface HistoryState {
  canUndo: boolean;
  canRedo: boolean;
  undoStack: HistoryItem[];
  redoStack: HistoryItem[];
  maxHistorySize: number;
  isPerformingAction: boolean;
}

/**
 * 历史记录管理器
 * 用于实现撤销/重做功能
 */
export const useHistoryStore = defineStore('history', {
  state: (): HistoryState => ({
    canUndo: false,
    canRedo: false,
    undoStack: [],
    redoStack: [],
    maxHistorySize: 50,
    isPerformingAction: false
  }),
  
  actions: {
    /**
     * 保存操作到历史记录
     * @param type 操作类型
     * @param data 操作数据
     * @param description 操作描述
     */
    saveAction(type: ActionType, data: { before: any, after: any }, description: string) {
      if (this.isPerformingAction) return;
      
      const historyItem: HistoryItem = {
        id: `history-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        type,
        timestamp: Date.now(),
        data,
        description
      };
      
      // 添加到撤销栈
      this.undoStack.push(historyItem);
      
      // 清空重做栈
      this.redoStack = [];
      
      // 限制历史记录大小
      if (this.undoStack.length > this.maxHistorySize) {
        this.undoStack.shift();
      }
      
      // 更新状态
      this.updateHistoryState();
      
      // 发送历史记录变更事件
      eventBus.emit('history:changed', {
        canUndo: this.canUndo,
        canRedo: this.canRedo
      });
    },
    
    /**
     * 撤销操作
     */
    undo() {
      if (!this.canUndo || this.isPerformingAction) return;
      
      this.isPerformingAction = true;
      
      const historyItem = this.undoStack.pop();
      if (!historyItem) {
        this.isPerformingAction = false;
        return;
      }
      
      // 添加到重做栈
      this.redoStack.push(historyItem);
      
      // 执行撤销操作
      this.executeAction(historyItem, 'undo');
      
      // 更新状态
      this.updateHistoryState();
      
      // 发送历史记录变更事件
      eventBus.emit('history:changed', {
        canUndo: this.canUndo,
        canRedo: this.canRedo
      });
      
      this.isPerformingAction = false;
    },
    
    /**
     * 重做操作
     */
    redo() {
      if (!this.canRedo || this.isPerformingAction) return;
      
      this.isPerformingAction = true;
      
      const historyItem = this.redoStack.pop();
      if (!historyItem) {
        this.isPerformingAction = false;
        return;
      }
      
      // 添加到撤销栈
      this.undoStack.push(historyItem);
      
      // 执行重做操作
      this.executeAction(historyItem, 'redo');
      
      // 更新状态
      this.updateHistoryState();
      
      // 发送历史记录变更事件
      eventBus.emit('history:changed', {
        canUndo: this.canUndo,
        canRedo: this.canRedo
      });
      
      this.isPerformingAction = false;
    },
    
    /**
     * 执行操作
     * @param historyItem 历史记录项
     * @param mode 模式（撤销/重做）
     */
    executeAction(historyItem: HistoryItem, mode: 'undo' | 'redo') {
      const { type, data } = historyItem;
      const actionData = mode === 'undo' ? data.before : data.after;
      
      // 根据操作类型执行相应的操作
      switch (type) {
        case 'element-add':
          this.handleElementAddAction(actionData, mode);
          break;
        case 'element-remove':
          this.handleElementRemoveAction(actionData, mode);
          break;
        case 'element-modify':
          this.handleElementModifyAction(actionData);
          break;
        case 'element-move':
          this.handleElementMoveAction(actionData);
          break;
        case 'element-resize':
          this.handleElementResizeAction(actionData);
          break;
        case 'element-rotate':
          this.handleElementRotateAction(actionData);
          break;
        case 'element-style-change':
          this.handleElementStyleChangeAction(actionData);
          break;
        case 'group-create':
          this.handleGroupCreateAction(actionData, mode);
          break;
        case 'group-ungroup':
          this.handleGroupUngroupAction(actionData, mode);
          break;
        case 'layer-reorder':
          this.handleLayerReorderAction(actionData);
          break;
        default:
          console.warn(`Unknown action type: ${type}`);
      }
      
      // 发送操作执行事件
      eventBus.emit('history:action-executed', {
        type,
        mode,
        data: actionData
      });
    },
    
    // 处理元素添加操作
    handleElementAddAction(actionData: any, mode: 'undo' | 'redo') {
      if (mode === 'undo') {
        // 撤销添加 = 删除元素
        eventBus.emit('element:remove', { elementId: actionData.id });
      } else {
        // 重做添加 = 添加元素
        eventBus.emit('element:add', { element: actionData });
      }
    },
    
    // 处理元素删除操作
    handleElementRemoveAction(actionData: any, mode: 'undo' | 'redo') {
      if (mode === 'undo') {
        // 撤销删除 = 添加元素
        eventBus.emit('element:add', { element: actionData });
      } else {
        // 重做删除 = 删除元素
        eventBus.emit('element:remove', { elementId: actionData.id });
      }
    },
    
    // 处理元素修改操作
    handleElementModifyAction(actionData: any) {
      eventBus.emit('element:update', {
        elementId: actionData.id,
        properties: actionData
      });
    },
    
    // 处理元素移动操作
    handleElementMoveAction(actionData: any) {
      eventBus.emit('element:move', {
        elementId: actionData.id,
        position: actionData.position
      });
    },
    
    // 处理元素调整大小操作
    handleElementResizeAction(actionData: any) {
      eventBus.emit('element:resize', {
        elementId: actionData.id,
        size: actionData.size
      });
    },
    
    // 处理元素旋转操作
    handleElementRotateAction(actionData: any) {
      eventBus.emit('element:rotate', {
        elementId: actionData.id,
        rotation: actionData.rotation
      });
    },
    
    // 处理元素样式变更操作
    handleElementStyleChangeAction(actionData: any) {
      eventBus.emit('element:style-change', {
        elementId: actionData.id,
        style: actionData.style
      });
    },
    
    // 处理组合创建操作
    handleGroupCreateAction(actionData: any, mode: 'undo' | 'redo') {
      if (mode === 'undo') {
        // 撤销组合 = 解组
        eventBus.emit('group:ungroup', { groupId: actionData.id });
      } else {
        // 重做组合 = 创建组合
        eventBus.emit('group:create', {
          elements: actionData.elements,
          groupId: actionData.id
        });
      }
    },
    
    // 处理组合解组操作
    handleGroupUngroupAction(actionData: any, mode: 'undo' | 'redo') {
      if (mode === 'undo') {
        // 撤销解组 = 创建组合
        eventBus.emit('group:create', {
          elements: actionData.elements,
          groupId: actionData.id
        });
      } else {
        // 重做解组 = 解组
        eventBus.emit('group:ungroup', { groupId: actionData.id });
      }
    },
    
    // 处理图层重排序操作
    handleLayerReorderAction(actionData: any) {
      eventBus.emit('layer:reorder', {
        layers: actionData.layers
      });
    },
    
    /**
     * 更新历史状态
     */
    updateHistoryState() {
      this.canUndo = this.undoStack.length > 0;
      this.canRedo = this.redoStack.length > 0;
    },
    
    /**
     * 清空历史记录
     */
    clearHistory() {
      this.undoStack = [];
      this.redoStack = [];
      this.canUndo = false;
      this.canRedo = false;
      
      // 发送历史记录变更事件
      eventBus.emit('history:changed', {
        canUndo: false,
        canRedo: false
      });
    },
    
    /**
     * 设置最大历史记录大小
     * @param size 最大历史记录大小
     */
    setMaxHistorySize(size: number) {
      this.maxHistorySize = size;
      
      // 如果当前历史记录超过新的最大大小，则裁剪
      if (this.undoStack.length > this.maxHistorySize) {
        this.undoStack = this.undoStack.slice(-this.maxHistorySize);
        this.updateHistoryState();
      }
    }
  }
});